package org.example.c_0_001;

import org.junit.Test;

public class T_Sleep_Yield_Join {

    @Test
    public void test(){
//        sleep();
//        yield();
        join();
    }

    /**
     * sleep演示
     * Thread.sleep()，暂停一个线程。并可以指定时间。
     */
    public void sleep(){
        new Thread(()->{
            System.out.println("sleep线程开始");
            try {
                Thread.sleep(3000L);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
            System.out.println("sleep线程结束");
        },"sleep").start();
        // 主线程等待其他线程执行完毕
        try {
            Thread.sleep(4000L);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
    }

    /**
     * yield演示
     * Thread.yield(),当前线程退出一下由操作系统重新调度。
     */
    public void yield(){
        Thread thread1 = new Thread(() -> {
            System.out.println("执行yield");
            Thread.yield();
            System.out.println("yield结束");
        },"yield1");
        Thread thread2 = new Thread(() -> {
            for (int i = 0; i < 10; i++) {
                System.out.println("线程2执行");
            }
        },"yield2");
        thread1.start();
        thread2.start();
        // 主线程等待其他线程执行完毕
        try {
            Thread.sleep(3000);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
    }

    /**
     * join演示
     * thread.join()，等待这个线程执行完后再执行。
     */
    public void join(){
        Thread thread = new Thread(() -> {
            for (int i = 0; i < 10; i++) {
                System.out.println("执行");
                try {
                    Thread.sleep(1000);
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            }
        },"join");
        thread.start();
        // 等待thread执行完毕
        try {
            thread.join();
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
    }
}
